package cn.anquing.util;

import com.fenqi.exceprion.UploadException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

public class FileUtil {
	
	private static Logger log  = LoggerFactory.getLogger(FileUtil.class);
	
	/**
	 * 获取唯一字符串 用于文件上件的随机名
	 */
	
	public static String getTimeRand(String filename) {
		StringBuffer buf = new StringBuffer();

		SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmssSSS");

		String timestamp = sdf.format(new Date());

		buf.append(timestamp);// 加上日期
		Random random = new Random();
		for (int i = 0; i < 5; i++) {
			buf.append(random.nextInt(10));// 取五个随机数追加到StringBuffer
		}

		int i = filename.lastIndexOf(".");// 返回最后一个点的位置
		String extension = filename.substring(i + 1);// 取出扩展名

		buf.append("." + extension);// 加上扩展名
		return buf.toString();

	}
	
	public static String saveFile(MultipartFile file) throws IllegalStateException, IOException{
		String fileName = file.getOriginalFilename();// 文件原名称
		fileName = getTimeRand(fileName);
		String path="/data/web/dida_img/user/headicon/"+fileName;
		file.transferTo(new File(path));
		return fileName;
	}
	
	public static String getRealPath(){	
		
		return System.getProperty("user.dir");
	}
	
	/**   
	* @Title: saveFile   
	* @Description:保存单个附件,默认大小为10M，默认类型为png,jpg
	* @param file
	* @param realPath
	* @param maxSize
	* @param type
	* @return   
	*/ 
	public static Map<String,String> saveFile(MultipartFile file,String realPath,Integer maxSize,String type){
		
		if(maxSize==null||maxSize==0){
			maxSize=10;
		}		
		if(type==null||Objects.equals("", type)){
			type="png,jpg";
		}
		
		Map<String, String> uploadResult = new HashMap<String,String>();
		
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
		String fileName = CodecUtil.getCurrTimeAndRandom()+"."+suffix;
		
		long size = file.getSize();
		log.info("文件大小为{}Btye",size);
		
        if(size>maxSize*1024*1024){
        	uploadResult.put("upload","f");
        	uploadResult.put("errorType","请上传小于"+maxSize+"M的文件!");
        	return uploadResult;
        }
        String fileSuffix = type;
        if(fileSuffix.indexOf(suffix)==-1){
        	uploadResult.put("upload","f");
        	uploadResult.put("errorType","仅支持"+type+"文件!");
        	return uploadResult;
        }        
        //保存 文件
        File targetFile = new File(realPath,fileName);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
            uploadResult.put("fileName",fileName);
            return uploadResult;
        } catch (Exception e) {
        	throw new UploadException("保存附件失败");
        }
		
	}
	
	/**   
	* @Title: uploadFile   
	* @Description:保存多个附件，返回附件名，附件url（多附件之间用','隔开）,默认大小为10M，默认类型为png,jpg
	* @param files
	* @param realPath
	* @param maxSize
	* @param type
	* @return   
	*/ 
	public static Map<String,String> uploadFile(MultipartFile[] files,String realPath,Integer maxSize,String type){
		Map<String,String> fileNameAndfileUrl = new HashMap<String, String>();
		
		if(maxSize==null||maxSize==0){
			maxSize=10;
		}
		if(type==null||Objects.equals("", type)){
			type="png,jpg";
		}
		
		//对文件名临时变量
		String fileNameT="";
		
		//定义数据名称
		StringBuilder dataNameSB= new StringBuilder();
		StringBuilder fileNameSB = new StringBuilder();
		String dataName="";
		String dataUrl="";
		
		boolean first= true;
		for (MultipartFile file:files){
			//第一个不需要逗号
			if(first){
				first=false;						
				fileNameT = file.getOriginalFilename();
				log.info("结算凭证文件名{}",fileNameT);
				dataNameSB.append(fileNameT);
				String suffix = fileNameT.substring(fileNameT.lastIndexOf(".") + 1).toLowerCase();
				String fileName = CodecUtil.getCurrTimeAndRandom()+"."+suffix;
				fileNameSB.append(fileName);
				
				//对附件进行过滤		       
		        long size = file.getSize();		       
		        if(size>maxSize*1024*1024){
		        	throw new UploadException("请上传小于"+maxSize+"M的文件!");
		        }		       
		        if(type.indexOf(suffix)==-1){
		        	throw new UploadException("仅支持"+type+"文件!");
		        }     
		        //保存 文件
		        File targetFile = new File(realPath,fileName);
		        if(!targetFile.exists()){
		            targetFile.mkdirs();
		        }        
		        try {
		            file.transferTo(targetFile);
		        } catch (Exception e) {
		        	throw new UploadException("保存附件失败");
		        }
			}else{
				fileNameT = file.getOriginalFilename();						
				dataNameSB.append(",");	
				dataNameSB.append(fileNameT);
				String suffix = fileNameT.substring(fileNameT.lastIndexOf(".") + 1).toLowerCase();
				String fileName = CodecUtil.getCurrTimeAndRandom()+"."+suffix;
				fileNameSB.append(",");
				fileNameSB.append(fileName);
				//对附件进行过滤		       
				long size = file.getSize();		       
		        if(size>maxSize*1024*1024){
		        	throw new UploadException("请上传小于"+maxSize+"M的文件!");
		        }		       
		        if(type.indexOf(suffix)==-1){
		        	throw new UploadException("仅支持"+type+"文件!");
		        }		        
		        //保存 文件
		        File targetFile = new File(realPath,fileName); 
		        if(!targetFile.exists()){
		            targetFile.mkdirs();           
		        }        
		        try {
		            file.transferTo(targetFile);
		        } catch (Exception e) {  
		        	throw new UploadException("保存附件失败");
		        }
			}			
		}
		
		dataName = dataNameSB.toString();
		dataUrl = fileNameSB.toString();
		
		fileNameAndfileUrl.put("fileName", dataName);
		fileNameAndfileUrl.put("fileUrl", dataUrl);
		
		return fileNameAndfileUrl;
		
	}


	/**

	 * @Title: saveUeditorFile

	 * @Description:保存单个附件,默认大小为10M，默认类型为png,jpg

	 * @param file

	 * @param realPath

	 * @param maxSize

	 * @param type

	 * @return

	 */
	public static Map<String,String> saveUploadOneFile(MultipartFile file,String realPath,Integer maxSize,String type){

		if(maxSize==null||maxSize==0){
			maxSize=10;
		}
		if(type==null||Objects.equals("", type)){
			type="png,jpg";
		}

		Map<String, String> uploadResult = new HashMap<String,String>();
		String fileName = file.getOriginalFilename();
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
		String saveFileName = CodecUtil.createOrderNo()+"."+suffix;

		long size = file.getSize();
		log.info("文件大小为{}Btye",size);

		if(size>maxSize*1024*1024){
			uploadResult.put("upload","f");
			uploadResult.put("errorType","请上传小于"+maxSize+"M的文件!");
			return uploadResult;
		}
		String fileSuffix = type;
		if(fileSuffix.indexOf(suffix)==-1){
			uploadResult.put("upload","f");
			uploadResult.put("errorType","仅支持"+type+"文件!");
			return uploadResult;
		}

		File parent = new File(realPath);
		if(!parent.exists()){
			parent.mkdirs();
		}
		//保存 文件
		File targetFile = new File(parent,saveFileName);

		log.info("保存路径：{}",targetFile.getPath());
//		System.out.println(targetFile.getPath());
		try {
			file.transferTo(targetFile);
			uploadResult.put("url",saveFileName);
			uploadResult.put("fileName",fileName);
			return uploadResult;
		} catch (Exception e) {
			e.printStackTrace();
			throw new UploadException("保存附件失败");
		}
	}

	/**
	 * 删除文件
	 * @param path 文件存放路径
	 */
	public static void deleteFileByPath(String path){
		File file = new File(path);
		if (file.exists()){
			file.delete();
		}
	}
}
